package com.dianganjiao.lib

import android.app.Activity
import android.app.Application
import android.content.Context
import android.text.TextUtils
import com.dianganjiao.lib.http.OkGoApi
import com.dianganjiao.lib.life.ActivityCallback
import com.dianganjiao.lib.util.SpUtil

/**
 * create file time : 2021/2/22
 * create user : wxl
 * subscribe :
 */
class AppContext private constructor() {

    private lateinit var context: Application
    private val activityCallback: ActivityCallback = ActivityCallback()


    companion object {
        val appContext = AC.ac
    }

    private object AC {
        val ac = AppContext()
    }

    fun init(context: Application, debug: Boolean) {
        this.context = context
        SpUtil.context = context
        AppConstant.debug = debug
        OkGoApi.api.setBaseUrl(AppConstant.baseUrl, context)
        this.context.registerActivityLifecycleCallbacks(activityCallback)
    }

    fun getApplication(): Application {
        return context
    }


    fun getCurrentActivity(): Activity? {
        return activityCallback.getCurrentActivity()
    }

    fun getActivity(): Activity {
        return activityCallback.getCurrentActivity()!!
    }

    fun isLogin(): Boolean {
        return !TextUtils.isEmpty(
            SpUtil.sp.getString(
                "token"
            )
        )
    }



    fun exitLogin() {
        SpUtil.sp.put("user", "")
        SpUtil.sp.put("token", "")
        SpUtil.sp.put("refreshToken", "")
    }



    /***
     * 获取版本号
     */
    fun getVersion(context: Context): String {
        try {
            val manager = context.getPackageManager()
            val info = manager.getPackageInfo(context.getPackageName(), 0)
            val version = info.versionName
            return version
        } catch (e: Exception) {
            return "无法获取到版本号"
        }
    }



}